import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/bean/home_ad_result.dart';
import 'package:flutter_app/bean/home_banner_result.dart';
import 'package:flutter_app/bean/home_hot_goods_result.dart';
import 'package:flutter_app/bean/home_recommend_result.dart';
import 'package:flutter_app/bean/home_top_navigator_result.dart';
import 'package:flutter_app/config/service_url.dart';
import 'package:flutter_app/service/service_method.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  String homePageBanner = "正在获取数据";
  int page = 1;
  List<HotGoodsListBean> hotGoodsList = [];

  //火爆专区标题
  Widget hotTitle = Container(
    margin: EdgeInsets.only(top: 10.0),
    padding: EdgeInsets.all(5.0),
    alignment: Alignment.center,
    decoration: BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(width: 0.5, color: Colors.black12))),
    child: Text("火爆专区"),
  );

  //火爆专区的list
  Widget _wrapList() {
    if (hotGoodsList != null) {
      List<Widget> listWidget = hotGoodsList.map((val) {
        return InkWell(
          onTap: () {
            print("点击了火爆商品");
          },
          child: Container(
            width: ScreenUtil().setWidth(372),
            color: Colors.white,
            padding: EdgeInsets.all(5.0),
            margin: EdgeInsets.only(bottom: 3.0),
            child: Column(
              children: <Widget>[
                Image.network("${val.goods_image_url}"),
                Text(
                  "${val.goods_name}",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Colors.pink, fontSize: ScreenUtil().setSp(26)),
                ),
                Row(
                  children: <Widget>[
                    Text("团购价:${val.min_group_price / 100}"),
                    Text(
                      "原价:${val.coupon_price}",
                      style: TextStyle(
                          color: Colors.black26,
                          decoration: TextDecoration.lineThrough),
                    )
                  ],
                )
              ],
            ),
          ),
        );
      }).toList();
      return Wrap(
        spacing: 2,
        children: listWidget,
      );
    } else {
      return Text("");
    }
  }

  Widget _hotGoods() {
    return Container(
      child: Column(
        children: <Widget>[hotTitle, _wrapList()],
      ),
    );
  }

  void _getHotGoods() {
    var formData = {"page": page};
    request("getGoodsHomePagSearch", formData, "get").then((value) {
      List<HotGoodsListBean> newList = HomeHotGoodsResult.fromJson(value)
          .entity
          .goods_search_response
          .goods_list;
      setState(() {
        hotGoodsList.addAll(newList);
        ++page;
      });
    });
  }

  @override
  void initState() {
    // getHomeBanner().then((value) {
    //   setState(() {
    //     homePageBanner = value.toString();
    //   });
    // });
    // request("getGoodsHomePagSearch", {"page": 1}, "get").then((value) {
    //   print(value);
    // });
    // print("页面初始化");
    _getHotGoods();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("百姓生活+"),
      ),
      body: EasyRefresh(
        onLoad: () async{
          _getHotGoods();
        },
        footer: ClassicalFooter(
          bgColor: Colors.white,
          textColor: Colors.pink,
          infoColor: Colors.pink,
          showInfo: true,
          noMoreText: "",
          infoText: "",
          loadReadyText: "释放立即加载",
          loadingText: "正在加载",
          loadedText: "加载完成",
          loadText: "上拉加载...",
        ),
        onRefresh: () async{

        },
        header: ClassicalHeader(
          bgColor: Colors.white,
          textColor: Colors.pink,
          infoColor: Colors.pink,
          showInfo: true,
          noMoreText: "",
          infoText: "",
          refreshingText:"正在刷新",
          refreshedText: "刷新完成",
          refreshText: "下拉刷新...",
          refreshReadyText: "释放立即刷新",
        ),
        child:SingleChildScrollView(
          child: Column(
            children: <Widget>[
              FutureBuilder(
                future: request("homePageBanner", null, "get"),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    List<HomeBannerBean> swipeDataList =
                        HomeBannerResult.fromJson(snapshot.data).entity;
                    return Column(
                      children: <Widget>[
                        SwiperDiy(
                          swiperDataList: swipeDataList,
                        )
                      ],
                    );
                  } else {
                    return Center(
                      child: Text("加载中"),
                    );
                  }
                },
              ),
              FutureBuilder(
                future: request("homeTopNavigator", null, "get"),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    List<HomeTopNavigatorBean> topNavigatorList =
                    HomeTopNavigatorResult.fromJson(snapshot.data).entity[0];
                    return Column(
                      children: <Widget>[
                        TopNavigator(
                          navigatorList: topNavigatorList,
                        )
                      ],
                    );
                  } else {
                    return Center(
                      child: Text("加载中"),
                    );
                  }
                },
              ),
              FutureBuilder(
                future: request("homeTopNavigator", null, "get"),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    List<HomeTopNavigatorBean> topNavigatorList =
                    HomeTopNavigatorResult.fromJson(snapshot.data).entity[1];
                    return Column(
                      children: <Widget>[
                        TopNavigator(
                          navigatorList: topNavigatorList,
                        )
                      ],
                    );
                  } else {
                    return Center(
                      child: Text("加载中"),
                    );
                  }
                },
              ),
              FutureBuilder(
                future: request("homeAD", null, "get"),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    List<HomeRecommendEntity> homeADList =
                        HomeADResult.fromJson(snapshot.data).entity.homeRecommend;
                    return Column(
                      children: <Widget>[
                        SwiperDiy(
                          homeADList: homeADList,
                        )
                      ],
                    );
                  } else {
                    return Center(
                      child: Text("加载中"),
                    );
                  }
                },
              ),
              FutureBuilder(
                future: request("homeRecommend", null, "get"),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    List<GoodsListBean> recommendList =
                        HomeRecommendResult.fromJson(snapshot.data)
                            .entity
                            .goods_search_response
                            .goods_list;
                    return RecommendWidget(
                      recommendList: recommendList,
                    );
                  } else {
                    return Center(
                      child: Text("加载中"),
                    );
                  }
                },
              ),
              _hotGoods(),
            ],
          ),
        ),
      )
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

//轮播图控件
class SwiperDiy extends StatelessWidget {
  final List<HomeBannerBean> swiperDataList;
  final List<HomeRecommendEntity> homeADList;

  const SwiperDiy({Key key, this.swiperDataList, this.homeADList})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334); //设计图尺寸宽高

    // print("设备的高度 "+"${ScreenUtil.screenHeight}");
    // print("设备的宽度 "+"${ScreenUtil.screenWidth}");
    // print("设备的像素密度 "+"${ScreenUtil.pixelRatio}");

    return Container(
      height: ScreenUtil().setHeight(swiperDataList != null ? 333 : 500),
      width: ScreenUtil().setWidth(750),
      child: Swiper(
        itemCount:
            swiperDataList != null ? swiperDataList.length : homeADList.length,
        itemBuilder: (context, index) {
          return Image.network(
            "${baseUrl + (swiperDataList != null ? swiperDataList[index].imagesUrl : homeADList[index].picture)}",
            fit: BoxFit.fill,
          );
        },
        // pagination: SwiperPagination(),//轮播图下面的点
        autoplay: true,
      ),
    );
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties
        .add(IterableProperty<HomeRecommendEntity>('homeADList', homeADList));
  }
}

//导航控件
class TopNavigator extends StatelessWidget {
  final List<HomeTopNavigatorBean> navigatorList;

  const TopNavigator({Key key, this.navigatorList}) : super(key: key);

  @override
  Widget _GridViewItemUI(BuildContext context, HomeTopNavigatorBean item) {
    return InkWell(
      onTap: () {
        print("点击了导航${item.opt_id}");
      },
      child: Column(
        children: <Widget>[
          Image.network(
            "${baseUrl + item.imagesUrl}",
            width: ScreenUtil().setWidth(95),
          ),
          Text("${item.title}")
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334); //设计图尺寸宽高
    return Container(
      height: ScreenUtil().setHeight(180),
      padding: EdgeInsets.all(3.0),
      child: GridView.count(
        crossAxisCount: 5,
        padding: EdgeInsets.all(4.0),
        children: navigatorList.map((item) {
          return _GridViewItemUI(context, item);
        }).toList(),
      ),
    );
  }
}

//推荐商品
class RecommendWidget extends StatelessWidget {
  final List<GoodsListBean> recommendList;

  const RecommendWidget({Key key, this.recommendList}) : super(key: key);

  //商品推荐标题
  Widget _titleWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),
      decoration: BoxDecoration(
          color: Colors.white,
          border:
              Border(bottom: BorderSide(width: 0.5, color: Colors.black12))),
      child: Text("商品推荐"),
    );
  }

  //商品推荐的item
  Widget _item(index) {
    return InkWell(
      onTap: () {},
      child: Container(
        height: ScreenUtil().setHeight(330),
        width: ScreenUtil().setWidth(250),
        padding: EdgeInsets.all(8.0),
        decoration: BoxDecoration(
            color: Colors.white,
            border:
                Border(left: BorderSide(width: 0.5, color: Colors.black12))),
        child: Column(
          children: <Widget>[
            Image.network("${recommendList[index].goods_image_url}"),
            Text("团购价: ${(recommendList[index].min_group_price) / 100}"),
            Text(
              "原价:${(recommendList[index].min_normal_price) / 100}",
              style: TextStyle(
                  decoration: TextDecoration.lineThrough,
                  color: Colors.grey), //原价中划线
            )
          ],
        ),
      ),
    );
  }

  //横向滚动的list
  Widget _recommendList() {
    return Container(
      height: ScreenUtil().setHeight(337),
      child: ListView.builder(
        itemBuilder: (context, index) {
          return _item(index);
        },
        itemCount: recommendList.length,
        scrollDirection: Axis.horizontal,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(397),
      margin: EdgeInsets.only(top: 10.0),
      child: Column(
        children: <Widget>[
          _titleWidget(),
          _recommendList(),
        ],
      ),
    );
  }
}
